<template>
  <div class="">
    <dl class="m-categroy">
      <dt>按拼音首字母选择：</dt>
      <dd
        v-for="item in list"
        :key="item">
        <a :href="'#city-'+item">{{ item }}</a>
      </dd>
    </dl>
    <dl
      v-for="item in block_list"
      :key="item.title"
      class="m-categroy-section">
      <dt :id="'city-'+item.title">{{ item.title }}</dt>
      <dd>
        <span
          v-for="c in item.city"
          :key="c">{{ c }}</span>
      </dd>
    </dl>
  </div>
</template>

<script>
import pyjs from 'js-pinyin'
export default {
  data(){
    return {
      list:'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
      block_list:[],
    }
  },
  async mounted(){
    let self=this;
    let blocks=[]
    let {status,data:{city}}=await self.$axios.get('/geo/city');
    if(status===200){
      let p 
      let c   
      let d={}   // 用来装{A:["安庆市","安阳市"],B:["北京"],...}
      city.forEach(item=>{
        p=pyjs.getFullChars(item.name).toUpperCase().slice(0,1)  // 获取大写的首字母
        c=p.charCodeAt(0)                  // 把首字母A..Z转化为数字的charCodeAt编码
        if(c>64&&c<90){
          if(!d[p]) return d[p]=[]     
          d[p].push(item.name)
        }
      })
      for(let [k,v] of Object.entries(d)){  // Object.entries()的遍历
        blocks.push({
          title:k,              //k:v  k是城市首字母:v是对应的城市名数组
          city:v
        })
      }
      blocks.sort((a,b)=>a.title.charCodeAt(0)-b.title.charCodeAt(0)) //排序重要
      self.block_list=blocks
    }
  }
}
</script>

<style lang="scss">
  @import "@/assets/css/changeCity/categroy.scss";
</style>
